const { defineConfig } = require("@vue/cli-service");
const { tab, questions } = require("./src/mock");
const bodyParser = require("body-parser");
const JWT = require("jsonwebtoken");
const key = "welkfnwldqlmwdlq";
const userList = [
  {
    username: "13171996138",
    password: "123456",
    nickname: "张三",
    avator: `https://robohash.org/${Math.random()
      .toString()
      .slice(2)}?set=set4`,
  },
  {
    username: "admin",
    password: "admin",
    nickname: "管理人",
    avator: `https://robohash.org/${Math.random()
      .toString()
      .slice(2)}?set=set4`,
  },
];
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    setupMiddlewares(middle, { app }) {
      app.use(bodyParser.json());
      app.get("/api/tab/list", (req, res) => {
        res.send({
          code: 200,
          data: tab,
        });
      });

      app.post("/api/post", (req, res) => {
        const { id } = req.body;
        let data = null;
        tab.forEach((v) => {
          const result = v.list.find((item) => item.id === id);
          if (result) data = result;
        });

        if (data) {
          res.send({
            code: 200,
            data: data,
          });
        } else {
          res.send({
            code: 404,
            data: null,
            message: "该文章已经下架！！！",
          });
        }
      });

      app.post("/api/login", (req, res) => {
        const { username, password } = req.body;

        const data = userList.find(
          (v) => v.username === username && v.password === password
        );

        if (data) {
          res.send({
            code: 200,
            data: {
              nickname: data.nickname,
              avator: data.avator,
              username: data.username,
              token: JWT.sign(
                {
                  nickname: data.nickname,
                  avator: data.avator,
                  username: data.username,
                },
                key
              ),
            },
          });
        } else {
          res.send({
            code: 401,
            data: null,
            message: "账户密码错误， 请重新登录",
          });
        }
      });

      app.get("/questions", (req, res) => {
        res.send({
          code: 200,
          data: questions,
        });
      });

      return middle;
    },
    // 请求代理
    // 代理到懂车帝 真实服务器
    proxy: {
      "/api": {
        target: "https://m.dcdapp.com/motor/brand/m/v1/brand/?device_id=0",
        pathRewrite: { "^/api": "" },
      },
      "/detail": {
        target: "https://m.dcdapp.com/motor/brand/m/v5/brand_series_list/",
        pathRewrite: { "^/detail": "" },
      },
    },
  },
});
